package com.xh.bussiness.exam.bean.dto;

import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.xh.bussiness.exam.constant.PaperTestConstant;
import com.xh.bussiness.exam.constant.UserErrorQuestionConstant;
import com.xh.bussiness.system.bean.dto.DictionaryBean;
import com.xh.bussiness.system.bean.dto.StudentBean;
import com.xh.bussiness.tiku.bean.dto.KnowledgeDto;
import com.xh.core.bean.BaseDto;
import com.xh.core.util.StringUtils;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.util.*;

/*
 * @Author daiwei
 * @Description
 * @Date 2019/11/5 11:23
 **/
@Data
@ApiModel("学生错题汇总统计BEAN")
public class StudentErrorTotalStatDto extends BaseDto {

    @ApiModelProperty("学员")
    private StudentBean student;
    @ApiModelProperty("年部")
    private DictionaryBean gradeType;
    @ApiModelProperty("学科")
    private DictionaryBean subject;
    @ApiModelProperty("错题总数")
    private Integer totalCount;
    @ApiModelProperty("薄弱知识点数")
    private Integer weekKnowledgeCount;
    @ApiModelProperty("平均难度")
    private Double avgDifficult=0D;
    @ApiModelProperty("一级知识点试题数")
    private List<KnowledgeDto> rootKnowledgeQuestionCountList=new ArrayList<>();
    @ApiModelProperty("错题原因数")
    private List<ErrorReasonCountBean> errorReasonQuestionCountList=new ArrayList<>();
    //错题难度分布
    @ApiModelProperty("错题难度分布")
    private List<StudentDifficultErrorQuestionStatBean> difficultStatCountList=new ArrayList<>();
    @JSONField(serialize=false)
    @JsonIgnore
    //临时变量，汇总难度统计
    private Map<Integer,StudentDifficultErrorQuestionStatBean> difficultStatCount=new LinkedHashMap<>();

    @JSONField(serialize=false)
    @JsonIgnore
    //临时变量，汇总知识点分析统计
    private Map<String,StudentKnowledgeStatChildBean> studentKnowledgeStatChildMap=new LinkedHashMap<>();


    @ApiModelProperty("知识点分析列表")
    private List<StudentKnowledgeStatRootBean> knowledgeStatList=new ArrayList<>();

    /**
     * 根据明细计算统计数值
     * @param errorStatList
     * @param testDetailStatList
     */
    public void calc(List<Map<String,Object>> errorStatList,List<Map<String,Object>> testDetailStatList){
        this.calcErrorQuestion(errorStatList);
        this.calcErrorQuestionTestDetail(testDetailStatList);
        //难度统计map转list
        this.difficultStatCountList.addAll(difficultStatCount.values());

        //汇总知识点分析
        Map<String,StudentKnowledgeStatRootBean> studentKnowledgeStatRootBeanMap=new LinkedHashMap<>();
        for(String thridKnowledgeId : studentKnowledgeStatChildMap.keySet()){
            StudentKnowledgeStatChildBean thirdKnowledge=studentKnowledgeStatChildMap.get(thridKnowledgeId);
            thirdKnowledge.setAvgDifficult(thirdKnowledge.getAvgDifficult()/thirdKnowledge.getErrorQuestionCount());
            //累加三级知识点数据，生成二级知识点数据
            StudentKnowledgeStatRootBean secondKnowledge=studentKnowledgeStatRootBeanMap.get(thirdKnowledge.getParentKnowledgeId());
            if(secondKnowledge==null){
                secondKnowledge=new StudentKnowledgeStatRootBean();
                secondKnowledge.setKnowledgeId(thirdKnowledge.getParentKnowledgeId());
                secondKnowledge.setKnowledgeName(thirdKnowledge.getParentKnowledgeName());
                studentKnowledgeStatRootBeanMap.put(thirdKnowledge.getParentKnowledgeId(),secondKnowledge);
            }
            secondKnowledge.setErrorQuestionCount(secondKnowledge.getErrorQuestionCount()+thirdKnowledge.getErrorQuestionCount());
            secondKnowledge.setExamQuestionCount(secondKnowledge.getExamQuestionCount()+thirdKnowledge.getExamQuestionCount());
            secondKnowledge.setFixedQuestionCount(secondKnowledge.getFixedQuestionCount()+thirdKnowledge.getFixedQuestionCount());
            secondKnowledge.getChilds().add(thirdKnowledge);

        }

        knowledgeStatList.addAll(studentKnowledgeStatRootBeanMap.values());
    }
    /**
     * 错题统计计算
     * @param errorStatList
     */
    private void calcErrorQuestion(List<Map<String,Object>> errorStatList){
        Map<String,KnowledgeDto> rootKnowledgeQuestionCountMap=new LinkedHashMap<>();
        Map<String,Integer> errorReasonQuestionCountMap=new LinkedHashMap<>();
        Map<String,Integer> errorQuestionCountMap=new HashMap<>();
        //薄弱知识点统计Map
        Map<String,Integer> weekKnowledgeMap=new LinkedHashMap<>();
        Integer difficultSum=0;
        for(Map<String,Object> item : errorStatList){
            String questionId=item.get("question_id").toString();
            String knowledgeId=item.get("knowledge_id").toString();
            String knowledgeName=item.get("knowledge_name").toString();
            String parentPath=(String)item.get("parent_path");
            String parentPathName=(String)item.get("parent_path_name");
            String errorReason=(String)item.get("error_reason");
            Integer diff=Integer.valueOf(item.get("difficult").toString());
            Integer fixedStatus=Integer.valueOf(item.get("fixed_status").toString());

            //判断当前是否计算过
            boolean isCurrentQuestionCount=errorQuestionCountMap.get(questionId)!=null;

            //一级知识点统计
            String rootId=null;
            String rootName=null;
            if(parentPath==null){
                rootId=knowledgeId;
                rootName=knowledgeName;
            }else{
                parentPath+=knowledgeId+"-";
                parentPathName+=knowledgeName+"-";
                String[] parentPaths=parentPath.split("-");
                String[] parentPathNames=parentPathName.split("-");
                try {
                    rootId=parentPaths[1];
                    rootName=parentPathNames[1];
                }catch (Exception ex){
                    System.out.println(ex.toString());
                }
            }
            //获取二三级知识点，没有留空
            String secondKnowledgeId="";
            String secondKnowledgeName="";
            String thirdKnowledgeId="";
            String thirdKnowledgeName="";
            if(parentPath!=null){
                String[] parentPaths=parentPath.split("-");
                String[] parentPathNames=parentPathName.split("-");
                try {
                    secondKnowledgeId=parentPaths[2];
                    secondKnowledgeName=parentPathNames[2];
                }catch (Exception ex){
                }
                try {
                    thirdKnowledgeId=parentPaths[3];
                    thirdKnowledgeName=parentPathNames[3];
                }catch (Exception ex){
                }
            }


            KnowledgeDto rootKnowledge=rootKnowledgeQuestionCountMap.get(rootId);

            if(rootKnowledge==null){
                rootKnowledge=new KnowledgeDto();
                rootKnowledge.setId(rootId);
                rootKnowledge.setName(rootName);
                rootKnowledge.setCount(1);
                rootKnowledgeQuestionCountMap.put(rootId,rootKnowledge);
            }else{
                rootKnowledge.setCount(rootKnowledge.getCount()+1);
            }
            //平均难度统计
            if(!isCurrentQuestionCount) {
                difficultSum += diff;
            }
            //错题难度分布
            StudentDifficultErrorQuestionStatBean studentDifficultErrorQuestionStatBean=difficultStatCount.get(diff);
            if(studentDifficultErrorQuestionStatBean==null){
                studentDifficultErrorQuestionStatBean=new StudentDifficultErrorQuestionStatBean();
                studentDifficultErrorQuestionStatBean.setDifficult(diff);
            }
            //三级知识点处理
            StudentKnowledgeStatChildBean studentKnowledgeStatChildBean= studentKnowledgeStatChildMap.get(secondKnowledgeId+"-"+thirdKnowledgeId);
            if(studentKnowledgeStatChildBean==null){
                studentKnowledgeStatChildBean=new StudentKnowledgeStatChildBean();
                studentKnowledgeStatChildBean.setKnowledgeId(thirdKnowledgeId);
                studentKnowledgeStatChildBean.setKnowledgeName(thirdKnowledgeName);
                studentKnowledgeStatChildBean.setParentKnowledgeId(secondKnowledgeId);
                studentKnowledgeStatChildBean.setParentKnowledgeName(secondKnowledgeName);
            }
            //难度累加，最后再平均
            studentKnowledgeStatChildBean.setAvgDifficult(studentKnowledgeStatChildBean.getAvgDifficult()+diff);

            //错题数
            if(!isCurrentQuestionCount) {
                studentDifficultErrorQuestionStatBean.setErrorQuestionCount(studentDifficultErrorQuestionStatBean.getErrorQuestionCount() + 1);
            }
            studentKnowledgeStatChildBean.setErrorQuestionCount(studentKnowledgeStatChildBean.getErrorQuestionCount()+1);
            //订正数
            if(fixedStatus.equals(UserErrorQuestionConstant.STATUS.FIXED)) {
                if(!isCurrentQuestionCount) {
                    studentDifficultErrorQuestionStatBean.setFixedQuestionCount(studentDifficultErrorQuestionStatBean.getFixedQuestionCount() + 1);
                }
                studentKnowledgeStatChildBean.setFixedQuestionCount(studentKnowledgeStatChildBean.getFixedQuestionCount()+1);
            }
            if(!isCurrentQuestionCount) {
                difficultStatCount.put(diff, studentDifficultErrorQuestionStatBean);
            }
            studentKnowledgeStatChildMap.put(secondKnowledgeId+"-"+thirdKnowledgeId,studentKnowledgeStatChildBean);

            //末级薄弱知识点计数
            weekKnowledgeMap.put(knowledgeId,1);

            //错题原因统计
            if(!isCurrentQuestionCount) {
                errorReason = errorReason == null ? "" : errorReason;
                String[] errorReasons = errorReason.split(",");
                for (String errorReasonItem : errorReasons) {
                    if (!StringUtils.isEmpty(errorReasonItem)) {
                        if (errorReasonQuestionCountMap.get(errorReasonItem) == null) {
                            errorReasonQuestionCountMap.put(errorReasonItem, 1);
                        } else {
                            errorReasonQuestionCountMap.put(errorReasonItem, errorReasonQuestionCountMap.get(errorReasonItem) + 1);
                        }
                    }
                }
            }
            errorQuestionCountMap.put(questionId,1);
        }
        //错题总数
        this.setTotalCount(errorQuestionCountMap.size());
        //统计总数
        this.setWeekKnowledgeCount(weekKnowledgeMap.size());
        //难度平均值
        this.setAvgDifficult(1.0*difficultSum/totalCount);
        //map转换成list
        this.rootKnowledgeQuestionCountList.addAll(rootKnowledgeQuestionCountMap.values());
        for(String item : errorReasonQuestionCountMap.keySet()){
            ErrorReasonCountBean errorReasonCountBean=new ErrorReasonCountBean();
            errorReasonCountBean.setErrorReason(item);
            errorReasonCountBean.setCount(errorReasonQuestionCountMap.get(item));
            errorReasonQuestionCountList.add(errorReasonCountBean);
        }
    }
    private void calcErrorQuestionTestDetail(List<Map<String,Object>> testDetailStatList){
        Map<String,Integer> errorQuestionCountMap=new HashMap<>();
        for(Map<String,Object> item : testDetailStatList) {
            String questionId=item.get("question_id").toString();
            String knowledgeId=item.get("knowledge_id").toString();
            String knowledgeName=item.get("knowledge_name").toString();
            String parentPath=(String)item.get("parent_path");
            String parentPathName=(String)item.get("parent_path_name");
            Integer diff=Integer.valueOf(item.get("difficult").toString());
            Integer answerResult=Integer.valueOf(item.get("answer_result").toString());
            //判断当前是否计算过
            boolean isCurrentQuestionCount=errorQuestionCountMap.get(questionId)!=null;

            //获取二三级知识点，没有留空
            String secondKnowledgeId="";
            String secondKnowledgeName="";
            String thirdKnowledgeId="";
            String thirdKnowledgeName="";
            if(parentPath!=null){
                parentPath+=knowledgeId+"-";
                parentPathName+=knowledgeName+"-";
                String[] parentPaths=parentPath.split("-");
                String[] parentPathNames=parentPathName.split("-");
                try {
                    secondKnowledgeId=parentPaths[2];
                    secondKnowledgeName=parentPathNames[2];
                }catch (Exception ex){
                }
                try {
                    thirdKnowledgeId=parentPaths[3];
                    thirdKnowledgeName=parentPathNames[3];
                }catch (Exception ex){
                }
            }

            //错题难度分布
            StudentDifficultErrorQuestionStatBean studentDifficultErrorQuestionStatBean=difficultStatCount.get(diff);
            if(studentDifficultErrorQuestionStatBean==null){
                studentDifficultErrorQuestionStatBean=new StudentDifficultErrorQuestionStatBean();
                studentDifficultErrorQuestionStatBean.setDifficult(diff);
            }
            //三级知识点处理
            StudentKnowledgeStatChildBean studentKnowledgeStatChildBean= studentKnowledgeStatChildMap.get(secondKnowledgeId+"-"+thirdKnowledgeId);
            if(studentKnowledgeStatChildBean==null){
                studentKnowledgeStatChildBean=new StudentKnowledgeStatChildBean();
                studentKnowledgeStatChildBean.setKnowledgeId(thirdKnowledgeId);
                studentKnowledgeStatChildBean.setKnowledgeName(thirdKnowledgeName);
                studentKnowledgeStatChildBean.setParentKnowledgeId(secondKnowledgeId);
                studentKnowledgeStatChildBean.setParentKnowledgeName(secondKnowledgeName);
            }

            //练习数
            if(!isCurrentQuestionCount) {
                studentDifficultErrorQuestionStatBean.setExamQuestionCount(studentDifficultErrorQuestionStatBean.getExamQuestionCount() + 1);
            }
            studentKnowledgeStatChildBean.setExamQuestionCount(studentKnowledgeStatChildBean.getExamQuestionCount()+1);
            //正确数
            if(answerResult.equals(PaperTestConstant.ANSWER_RESULT.RIGHT)) {
                if(!isCurrentQuestionCount) {
                    studentDifficultErrorQuestionStatBean.setExamRightQuestionCount(studentDifficultErrorQuestionStatBean.getExamRightQuestionCount() + 1);
                }
            }
            difficultStatCount.put(diff,studentDifficultErrorQuestionStatBean);
            studentKnowledgeStatChildMap.put(secondKnowledgeId+"-"+thirdKnowledgeId,studentKnowledgeStatChildBean);

            errorQuestionCountMap.put(questionId,1);
        }
    }

    @Data
    @ApiModel("错题原因数量Bean")
    class ErrorReasonCountBean{
        @ApiModelProperty("原因")
        private String errorReason;
        @ApiModelProperty("数量")
        private Integer count;
    }

    @Data
    @ApiModel("学生按难度错题分析BEAN")
    class StudentDifficultErrorQuestionStatBean{
        @ApiModelProperty("难度")
        private Integer difficult;
        @ApiModelProperty("错题数")
        private Integer errorQuestionCount=0;
        @ApiModelProperty("订正数")
        private Integer fixedQuestionCount=0;
        @ApiModelProperty("练习数")
        private Integer examQuestionCount=0;
        @ApiModelProperty("练习正确数")
        private Integer examRightQuestionCount=0;
    }

    @Data
    @ApiModel("学生按知识点错题分析根节点BEAN")
    class StudentKnowledgeStatRootBean{
        @ApiModelProperty("知识点id")
        private String knowledgeId;
        @ApiModelProperty("知识点名称")
        private String knowledgeName;
        @ApiModelProperty("错题数")
        private Integer errorQuestionCount=0;
        @ApiModelProperty("练习数")
        private Integer examQuestionCount=0;
        @ApiModelProperty("订正数")
        private Integer fixedQuestionCount=0;
        @ApiModelProperty("子集知识点")
        private List<StudentKnowledgeStatChildBean> childs=new ArrayList<>();
    }

    @Data
    @ApiModel("学生按知识点错题分析子节点BEAN")
    class StudentKnowledgeStatChildBean{
        @ApiModelProperty("父级知识点id")
        private String parentKnowledgeId;
        @ApiModelProperty("父级知识点名称")
        private String parentKnowledgeName;
        @ApiModelProperty("知识点id")
        private String knowledgeId;
        @ApiModelProperty("知识点名称")
        private String knowledgeName;
        @ApiModelProperty("平均难度")
        private Double avgDifficult=0D;
        @ApiModelProperty("错题数")
        private Integer errorQuestionCount=0;
        @ApiModelProperty("练习数")
        private Integer examQuestionCount=0;
        @ApiModelProperty("订正数")
        private Integer fixedQuestionCount=0;
    }
}
